<template>
  <div class="art-full-height">
    <!-- 搜索栏 -->
    <ArtSearchBar
      v-model="searchForm"
      :items="formItems"
      :show-expand="true"
      @search="handleSearch"
      @reset="resetSearchParams"
    />

    <ElCard class="art-table-card" shadow="never">
      <ArtTableHeader
        v-model:columns="columnChecks"
        v-model:showSearchBar="showSearchBar"
        :loading="loading"
        @refresh="refreshData"
      >
        <template #left>
          <ElSpace wrap>
            <ElButton type="primary" @click="handleAdd"> 添加商品 </ElButton>
          </ElSpace>
        </template>
      </ArtTableHeader>

      <!-- 积分商品表格 -->
      <ArtTable
        :loading="loading"
        :data="data"
        :columns="columns"
        :pagination="pagination"
        :show-overflow-tooltip="true"
        @pagination:size-change="handleSizeChange"
        @pagination:current-change="handleCurrentChange"
      >
        <!-- 商品图片列 -->
        <template #scorePhoto="{ row }">
          <div v-if="row.scorePhoto" class="image-preview">
            <ElImage
              :src="row.scorePhoto"
              :preview-src-list="[row.scorePhoto]"
              fit="cover"
              class="product-img"
              :preview-teleported="true"
            />
          </div>
          <span v-else class="text-gray-400">无图片</span>
        </template>

        <!-- 积分 -->
        <template #scoreCnt="{ row }">
          <span>{{ (row.scoreCnt || 0).toLocaleString() }} 积分</span>
        </template>

        <!-- 库存 -->
        <template #scoreStockNum="{ row }">
          <span>{{ (row.scoreStockNum || 0).toLocaleString() }} 件</span>
        </template>

        <!-- 上架状态 -->
        <template #scoreUpFlag="{ row }">
          {{ row.scoreUpFlag === 1 ? '下架' : row.scoreUpFlag === 2 ? '上架' : '未知' }}
        </template>

        <!-- 创建时间格式化 -->
        <template #createTime="{ row }">
          {{ formatDateTime(row.createTime) }}
        </template>

        <!-- 操作列 -->
        <template #operation="{ row }">
          <div class="flex items-center gap-2">
            <ArtButtonTable type="view" @click="handleView(row)"> 查看 </ArtButtonTable>
            <ArtButtonTable type="edit" @click="handleEdit(row)"> 编辑 </ArtButtonTable>
            <ArtButtonTable type="more" @click="handleInventory(row)"> 库存 </ArtButtonTable>
            <ArtButtonTable type="delete" @click="handleDelete(row)"> 删除 </ArtButtonTable>
          </div>
        </template>
      </ArtTable>
    </ElCard>
    <!-- 编辑/添加弹框 -->
    <ElDialog
      v-model="editDialogVisible"
      :title="isEditMode ? '编辑积分商品' : '添加积分商品'"
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="closePopEvent"
    >
      <ElForm ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="120px">
        <ElFormItem label="商品名称" prop="scoreName">
          <ElInput
            v-model="editForm.scoreName"
            placeholder="请输入商品名称"
            maxlength="50"
            show-word-limit
          />
        </ElFormItem>

        <ElFormItem label="商品积分" prop="scoreCnt">
          <ElInputNumber
            v-model.number="editForm.scoreCnt"
            :min="0"
            :step="1"
            placeholder="请输入商品积分"
            style="width: 100%"
          />
        </ElFormItem>

        <ElFormItem label="库存数量" prop="scoreStockNum">
          <ElInputNumber
            v-model.number="editForm.scoreStockNum"
            :min="0"
            :step="1"
            placeholder="请输入库存数量"
            style="width: 100%"
            :disabled="isEditMode"
          />
        </ElFormItem>

        <ElFormItem label="上架状态" prop="scoreUpFlag">
          <ElSelect v-model="editForm.scoreUpFlag" placeholder="请选择上架状态">
            <ElOption label="下架" :value="1" />
            <ElOption label="上架" :value="2" />
          </ElSelect>
        </ElFormItem>

        <ElFormItem label="商品图片" prop="scorePhoto">
          <proUploadImg
            v-model:fileList="scorePhoto"
            action="/api/api/ossFile/saveFile"
            :limit="1"
            accept=".jpg,.png,.jpeg"
            :max-size="2"
            size-unit="MB"
            upload-text="点击上传"
            tip="jpg/png/jpeg格式，且不超过2MB"
          />
        </ElFormItem>

        <ElFormItem label="商品描述" prop="scoreInfo">
          <ElInput
            v-model="editForm.scoreInfo"
            type="textarea"
            :rows="4"
            placeholder="请输入商品描述"
            maxlength="500"
            show-word-limit
          />
        </ElFormItem>
      </ElForm>

      <template #footer>
        <ElSpace>
          <ElButton @click="closePopEvent">取消</ElButton>
          <ElButton type="primary" @click="handleEditSubmit" :loading="editLoading">
            确认{{ isEditMode ? '修改' : '添加' }}
          </ElButton>
        </ElSpace>
      </template>
    </ElDialog>
    <ModifyInventory
      v-model="editInventoryDialogVisible"
      :act-data="currentAreaData"
      @success="handleDialogSuccess"
    />
    <LookProductDetails
      :dialogVisible="lookProductDetailsVisible"
      :act-data="productDetails"
      @closeEvent="((lookProductDetailsVisible = false), (productDetails = null))"
    />
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, onMounted, watch } from 'vue'
  import {
    dayjs,
    ElMessage,
    ElMessageBox,
    ElImage,
    ElDialog,
    ElForm,
    ElFormItem,
    ElInput,
    ElButton,
    ElSpace
  } from 'element-plus'
  import { useTable } from '@/composables/useTable'
  import ArtSearchBar from '@/components/core/forms/art-search-bar/index.vue'
  import ArtTable from '@/components/core/tables/art-table/index.vue'
  import ArtButtonTable from '@/components/core/forms/art-button-table/index.vue'
  import proUploadImg from '@/components/core/proUploadImg/index.vue'
  import ModifyInventory from './modules/modifyInventory.vue'
  import LookProductDetails from './modules/lookProductDetails.vue'
  import {
    scoGoodsPageDataUsingPost,
    scoGoodsGetDataUsingPost,
    scoGoodsSaveDataUsingPost,
    scoGoodsUpdateDataUsingPost,
    scoGoodsDeleteDataUsingPost,
    ScoGoodsVo
  } from '@/api'

  // 搜索表单
  const searchForm = ref({
    scoreName: undefined,
    scoreUpFlag: undefined
  })
  // 搜索表单配置
  const formItems = computed(() => {
    const currentForm = searchForm.value
    return [
      {
        key: 'scoreName',
        label: '商品名称',
        type: 'input',
        props: {
          placeholder: '请输入商品名称',
          value: currentForm.scoreName || ''
        },
        onInput: (val: string) => {
          searchForm.value.scoreName = val.trim() || undefined
        }
      },
      {
        key: 'scoreUpFlag',
        label: '上架状态',
        type: 'select',
        onClear: () => {
          searchForm.value.scoreUpFlag = undefined
        },
        props: {
          placeholder: '请选择上架状态',
          clearable: true,
          options: [
            { label: '上架', value: 2 },
            { label: '下架', value: 1 }
          ]
        }
      }
    ]
  })

  // 使用 useTable 管理表格数据
  const {
    columns,
    columnChecks,
    data,
    loading,
    pagination,
    getData,
    searchParams,
    handleSizeChange,
    handleCurrentChange,
    refreshData
  } = useTable({
    core: {
      apiFn: scoGoodsPageDataUsingPost,
      apiParams: {
        body: {
          current: 1,
          size: 10,
          scoreName: undefined,
          scoreUpFlag: undefined
        }
      },
      paginationWrapper: 'body',
      columnsFactory: () => [
        {
          prop: 'id',
          label: '商品ID',
          width: 100
        },
        {
          prop: 'scoreName',
          label: '商品名称',
          minWidth: 180
        },
        {
          prop: 'scorePhoto',
          label: '商品图片',
          width: 120,
          useSlot: true
        },
        {
          prop: 'scoreCnt',
          label: '商品积分',
          width: 120,
          useSlot: true
        },
        {
          prop: 'scoreStockNum',
          label: '库存数量',
          width: 120,
          useSlot: true
        },
        {
          prop: 'scoreUpFlag',
          label: '上架状态',
          width: 100,
          align: 'center',
          headerAlign: 'center',
          useSlot: true,
          formatter: (row: any) =>
            row.scoreUpFlag == 1 ? '下架' : row.scoreUpFlag == 2 ? '上架' : '未知'
        },
        {
          prop: 'createTime',
          label: '创建时间',
          width: 200,
          align: 'center',
          headerAlign: 'center',
          useSlot: true
        },
        {
          prop: 'operation',
          label: '操作',
          width: 230,
          fixed: 'right',
          align: 'center',
          headerAlign: 'center',
          useSlot: true
        }
      ]
    }
  })

  const showSearchBar = ref(false)

  // 编辑相关
  const editDialogVisible = ref(false)
  const editLoading = ref(false)
  const editFormRef = ref()
  const editForm = ref({
    id: 0,
    scoreName: '',
    scoreCnt: 0,
    scoreStockNum: 0,
    scoreUpFlag: 1,
    scorePhoto: '',
    scoreInfo: ''
  })
  const isEditMode = ref(false)

  // 图片上传相关
  const scorePhoto = ref<{ url: string }[]>([])

  // 监听图片变化同步到表单
  watch(
    scorePhoto,
    (newVal) => {
      if (newVal.length > 0) {
        editForm.value.scorePhoto = newVal[0].url
      } else {
        editForm.value.scorePhoto = ''
      }
    },
    { deep: true }
  )
  // 页面加载时自动获取数据
  onMounted(() => {
    getData()
  })

  const handleSearch = () => {
    searchParams.body.scoreName = searchForm.value.scoreName || undefined
    searchParams.body.scoreUpFlag = searchForm.value.scoreUpFlag || undefined
    getData()
  }

  const resetSearchParams = () => {
    // 重置搜索参数
    searchParams.body.scoreName = undefined
    searchParams.body.scoreUpFlag = undefined

    // 重置表单数据
    searchForm.value.scoreName = undefined
    searchForm.value.scoreUpFlag = undefined

    // 重新获取数据
    getData()
  }
  // 编辑表单验证规则
  const editFormRules = {
    scoreName: [
      { required: true, message: '请输入商品名称', trigger: 'blur' },
      { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    scoreCnt: [
      { required: true, message: '请输入商品积分', trigger: 'blur' },
      { type: 'number', min: 0, message: '商品积分不能小于0', trigger: 'blur' }
    ],
    scoreStockNum: [
      { required: true, message: '请输入库存数量', trigger: 'blur' },
      { type: 'number', min: 0, message: '库存数量不能小于0', trigger: 'blur' }
    ],
    scoreUpFlag: [{ required: true, message: '请选择上架状态', trigger: 'change' }],
    scorePhoto: [
      {
        required: true,
        message: '请上传商品图片',
        trigger: 'change',
        validator: (rule, value, callback) => {
          if (scorePhoto.value.length === 0) {
            callback(new Error('请上传商品图片'))
            return
          }
          callback()
        }
      }
    ]
  }
  // 格式化日期时间
  const formatDateTime = (dateTime?: string) => {
    return dateTime ? dayjs(dateTime).format('YYYY-MM-DD HH:mm:ss') : ''
  }
  const productDetails = ref<any>(null)
  const lookProductDetailsVisible = ref(false)
  // 查看详情
  const handleView = async (row: ScoGoodsVo) => {
    try {
      // 调用接口获取详情
      const res = await scoGoodsGetDataUsingPost({
        body: {
          id: row.id
        }
      })
      lookProductDetailsVisible.value = true
      productDetails.value = res
    } catch (error) {
      console.error('获取详情失败:', error)
      ElMessage.error('获取详情失败')
    }
  }

  // 添加商品
  const handleAdd = () => {
    // 重置表单
    closePopEvent()
    editFormRef.value?.resetFields()
    // 重置图片列表
    scorePhoto.value = []
    isEditMode.value = false
    editDialogVisible.value = true
  }

  // 编辑
  const handleEdit = (row: any) => {
    // 设置表单数据
    editForm.value = JSON.parse(JSON.stringify(row))
    // 设置图片列表
    if (row.scorePhoto) {
      scorePhoto.value = [{ url: row.scorePhoto }]
    } else {
      scorePhoto.value = []
    }

    isEditMode.value = true
    editDialogVisible.value = true
  }

  // 删除
  const handleDelete = async (row: ScoGoodsVo) => {
    try {
      await ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })

      await scoGoodsDeleteDataUsingPost({
        body: {
          id: row.id
        }
      })

      ElMessage.success('删除成功')
      getData()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }

  // 添加/编辑提交
  const handleEditSubmit = async () => {
    try {
      // 验证表单
      await editFormRef.value?.validate()
      if (editLoading.value) return
      editLoading.value = true
      // 准备提交数据
      const submitData: any = {
        scoreName: editForm.value.scoreName,
        scoreCnt: editForm.value.scoreCnt,
        scoreStockNum: editForm.value.scoreStockNum,
        scoreUpFlag: editForm.value.scoreUpFlag,
        scorePhoto: editForm.value.scorePhoto,
        scoreInfo: editForm.value.scoreInfo
      }

      // 如果是编辑模式，添加ID
      if (isEditMode.value) {
        submitData.id = editForm.value.id
      }
      if (isEditMode.value) {
        // 编辑商品
        await scoGoodsUpdateDataUsingPost({
          body: submitData
        })
      } else {
        // 添加商品
        await scoGoodsSaveDataUsingPost({
          body: submitData
        })
      }
      ElMessage.success(isEditMode.value ? '编辑成功' : '新增成功')
      getData()
      closePopEvent()
    } catch (error) {
      console.error(isEditMode.value ? '修改失败:' : '添加失败:', error)
      ElMessage.error(isEditMode.value ? '修改失败' : '添加失败')
    } finally {
      editLoading.value = false
    }
  }
  // 关闭弹框
  const closePopEvent = () => {
    editForm.value = {
      id: 0,
      scoreName: '',
      scoreCnt: 0,
      scoreStockNum: 0,
      scoreUpFlag: 1,
      scorePhoto: '',
      scoreInfo: ''
    }
    editFormRef.value?.resetFields()
    editDialogVisible.value = false
  }
  const editInventoryDialogVisible = ref(false)
  const currentAreaData = ref<any>(null)
  const handleInventory = (row: any) => {
    editInventoryDialogVisible.value = true
    currentAreaData.value = row
  }
  const handleDialogSuccess = () => {
    editInventoryDialogVisible.value = false
    currentAreaData.value = null
    getData()
  }
</script>

<style lang="scss" scoped>
  .image-preview {
    .product-img {
      width: 60px;
      height: 60px;
      cursor: pointer;
      object-fit: cover;
      border-radius: 4px;
    }

    .view-product-img {
      max-width: 300px;
      max-height: 300px;
      object-fit: cover;
      border-radius: 4px;
    }
  }

  .text-gray-400 {
    font-size: 12px;
    color: #9ca3af;
  }

  .detail-container {
    .detail-item {
      margin-bottom: 16px;

      label {
        display: inline-block;
        min-width: 120px;
        margin-right: 8px;
        font-weight: 600;
        color: #606266;
      }

      span {
        color: #303133;
      }

      .detail-content {
        padding: 8px 12px;
        margin-top: 4px;
        line-height: 1.5;
        color: #303133;
        word-break: break-word;
        white-space: pre-wrap;
        background-color: #f5f7fa;
        border-radius: 4px;
      }
    }
  }

  .loading-container {
    padding: 20px;
  }
</style>
